import React from 'react';
// const TransTable = props => {
//   const { handleAdd, columns, dataSource = [] } = props
//   const renderTitle = () => {

//   }
//   return (
//     <Row>
//       <Col>
//             运送方式： 除指定地区外，其余地区的运费采用“默认运费”
//       </Col>
//       <Col offset={22}>
//         <Button type="primary" onClick={handleAdd}>新增</Button>
//       </Col>
//       <Table 
//         columns={columns}
//         dataSource={dataSource}
//         rowKey={rowKey => rowKey}
//       />
//       <>
//         {renderTitle()}
//       </>
//     </Row>
//   );
// };

import { Table, Input, Button, Popconfirm, Form, Row, Col, InputNumber, } from 'antd';
import { connect } from 'dva';
import FormItem from 'antd/lib/form/FormItem';

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class TransTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '运送到',
        dataIndex: 'districtNames',
        key: 'districtNames',
        render: (text, record, i) => 
        <a onClick={this.changeModalStuaus.bind(this, i)}>
          {props.trans.proName || record.districtNames ? (props.trans.proName || record.districtNames) : '点击选择地区'}
        </a>,
      },
      {
        title: '首件',
        dataIndex: 'firstAmount',
        key: 'firstAmount',
        editable: true,
      },
      {
        title: '首费',
        dataIndex: 'firstCost',
        key: 'firstCost',
        editable: true,
      },
      {
        title: '续件',
        dataIndex: 'addAmount',
        key: 'addAmount',
        editable: true,
      },
      {
        title: '续费',
        dataIndex: 'addCost',
        key: 'addCost',
        editable: true,
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, record, i) => <><a onClick={() => this.handleDelete(i)}>删除</a></>
      },
    ];

    this.state = {
      dataSource: [],
      count: 0,
      params: {},
    };
  }  

  changeModalStuaus = (i) => {
    const { trans } = this.props
    this.props.dispatch({
      type: 'trans/update',
      payload: {
        modalStatus: !trans.modalStatus,
      }
    })
    this.props.dispatch({
      type: 'trans/update',
      payload: {
        current: i
      }
    })
  }

  handleDelete = key => {
    const { isEdit, dispatch } = this.props
    const dataSource = isEdit.types ? isEdit.types : [...this.state.dataSource];
    
    this.setState({ dataSource: dataSource.filter((item, index) => index != key) }, () => {
      dispatch({
        type: 'trans/update',
        payload: {
          record: this.state.dataSource,
        }
      })
    });
  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const { dispatch } = this.props
    const newData = {
      key: count,
      firstAmount: 10,
      firstCost: 10,
      addAmount: 10,
      addCost: 10,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
    dispatch({
      type: 'trans/update',
      payload: {
        record: [...dataSource, newData]
      }
    })
  };

  handleSave = row => {
    const { dispatch } = this.props
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource: newData });
    dispatch({
      type: 'trans/update',
      payload: {
        record: newData
      }
    })
  };

  handleParams = (param, val) => {
    this.state.params[param] =  val

    this.setState({params: this.state.params}, () => {
      this.props.dispatch({
        type: 'trans/update',
        payload: {
          params: {
            ...this.state.params
          }
        }
      })
    })
  }

  render() {
    const { dataSource } = this.state;
    const { isEdit, trans } = this.props
    const { details } = trans
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Row>
        <Col offset={1}>
          运送方式： 除指定地区外，其余地区的运费采用“默认运费”
        </Col>
        <Col>
          <Row style={{ marginTop: 30, marginLeft: 20}}>
            <Col span={2}><span>默认运费</span></Col>
            <Col span={2}>
              <InputNumber
                defaultValue={details.firstAmount} 
                onChange={v => this.handleParams('firstAmount', v)} 
              />
            </Col>
            <Col span={1}><span>件内，</span></Col>
            <Col span={2}>
              <InputNumber 
                defaultValue={details.addAmount} 
                onChange={v => this.handleParams('addAmount', v)} 
              />
            </Col>
            <Col span={2}><span>元；每增加</span></Col>
            <Col span={2}>
              <InputNumber 
                onChange={v => this.handleParams('firstCost', v)} 
                defaultValue={details.firstCost} 
              />
            </Col>
            <Col span={2}><span>件 增加运费</span></Col>
            <Col span={3}>
              <InputNumber 
                defaultValue={details.addCost} 
                onChange={v => this.handleParams('addCost', v)} 
              />
            </Col>
            <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
              新增
            </Button>
          </Row>
        </Col>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource.length == 0 ? isEdit.types : dataSource}
          columns={columns}
          rowKey={r => r.id || r.key}
        />
      </Row>
    );
  }
}

export default connect(({ trans }) => ({
  trans,
}))(TransTable)